from datetime import datetime

from django.shortcuts import render_to_response, get_object_or_404
from django.db.models import Q
from django.contrib.auth.decorators import login_required
from django.http import Http404, HttpResponseRedirect, HttpResponseForbidden, HttpResponse
from django.contrib.comments.models import *
from django.contrib.auth.models import User
from django.template import RequestContext

from django.views.generic.create_update import delete_object

from pypsqueak.page.models import *
from pypsqueak.page.forms import *
from pypsqueak.group.models import Group, Membership
from pypsqueak.chrome.models import *
from pypsqueak.chrome.forms import *
from pypsqueak.artifact.forms import *
from pypsqueak.versioning.models import *

def site_index(request):
	""" Show an activity page for the entire site """

	title = 'Site Homepage'
	breacrumb = ""

	users = User.objects.all()[:20]
	groups = Group.objects.all()[:20]
	versions = Version.objects.filter(model_name='Page')[:50]
	comments = Comment.objects.all().order_by('-submit_date')[:50]

	return render_to_response('page/site_index.html', locals() ,
							context_instance=RequestContext(request) )


def page_list(request, username):
	""" Show the list of pages for a user """

	user = get_object_or_404(User, username=username)
	profile = add_model_chrome(user.get_profile(),request)

	pages_header = child_model_chrome_list_header("My Pages", Page, request.user,user)
	groups = Membership.objects.filter(user=user)

	pagetree = PageTreeNavigationWidget( user, None )

	breadcrumb = ChromeBreadcrumbForm()
	breadcrumb.append(user.get_absolute_url(),user.get_short_name())

	versions = Version.objects.filter(user=user,model_name='Page')[:10]
	comments = Comment.objects.filter(user=user).order_by('-submit_date')[:10]

	return render_to_response('page/page_list.html', locals() ,
							context_instance=RequestContext(request) )


def page_read(request, username, slug):
	""" Select a page """

	user = get_object_or_404(User, username=username)
	profile = add_model_chrome(user.get_profile(),request)

	pages = Page.objects.filter( user__username = username, slug=urlquote(slug) )

	# No page found. If perms, then route to create.  Otherwise, fail.
	if len(pages) < 1 :
		if not Page.insert_permission(user, request.user):
			raise Http404()
		else:
			return HttpResponseRedirect( Page.get_insert_url(user) )
	else:
		page = add_model_chrome(pages[0], request)
		if not page.permission(request.user,'select'):
			return HttpResponseForbidden()
		# Loads artifacts in proper order using model Meta
		artifacts = PageArtifact.objects.filter(page=page)
		print artifacts[0].get_absolute_url()

	if request.GET.get('popup',0) == 0:
		# Normal Response
		pagetree = PageTreeNavigationWidget( page.user, page )

		# Load breadcrumb of parent pages.
		breadcrumb = ChromeBreadcrumbForm()
		breadcrumb.append(user.get_absolute_url(),user.first_name)
		for p in page.getParentTree():
			breadcrumb.append(p.get_absolute_url(),p.title)

		return render_to_response('page/page_detail.html', locals() ,
								context_instance=RequestContext(request) )
	else:
		# Provide pop-up response.
		return render_to_response('page/page_popup.html', locals() ,
							context_instance=RequestContext(request) )

@login_required
def page_insert(request, username, title = ''):
	""" Create a new page. Blank or based off of assignment template """

	user = get_object_or_404(User, username=username)
	profile = add_model_chrome(user.get_profile(),request)

	if not Page.insert_permission(user, request.user):
		raise HttpResponseForbidden()

	if request.method == 'POST':
		form = PageInsertForm(request.POST)
		template = int(request.POST['GroupAssignmentChoiceWidget'])

		new_page = Page()
		new_page.user = user
		new_page.save()

		if( template != -1 ):
			a = get_object_or_404(Assignment, pk=template)
			a.InitializePage( new_page )

		return HttpResponseRedirect( new_page.get_update_url() )
	else:
		form = PageInsertForm()

	# Load breadcrumb of parent pages.
	breadcrumb = ChromeBreadcrumbForm()
	breadcrumb.append(user.get_absolute_url(),user.first_name)

	return render_to_response('page/page_insert.html', locals(),
							context_instance=RequestContext(request) )


@login_required
def page_update(request, username, slug ):
	""" Update an existing page """

	page = get_object_or_404(Page, user__username = username, slug=urlquote(slug) )
	user = page.user
	profile = add_model_chrome(user.get_profile(),request)

	if not page.permission(request.user,'update'):
		return HttpResponseForbidden()

	forms = ComboForm()

	forms.add_form(PageUpdateForm, instances=page, request=request)
	forms.add_form(PageArtifactInlineUpdateForm,
		instances=PageArtifact.objects.filter(page=page),
		request=request)

	if request.method == 'POST':
		if forms.is_valid():
			forms.save()
			request.user.message_set.create(message='Page updated')
			return HttpResponseRedirect(page.get_absolute_url())

	# Add after save, as we only save the add form via ajax.
	forms.add_dependent_form(PageArtifactAjaxInsertForm, page)

	# Load similar pages and dispay in a widget.
	SimilarPages = Page.objects.all()[:20]

	# Load breadcrumb of parent pages.
	breadcrumb = ChromeBreadcrumbForm()
	breadcrumb.append(user.get_absolute_url(),user.first_name)
	for p in page.getParentTree():
		breadcrumb.append(p.get_absolute_url(),p.title)
	breadcrumb.append(page.get_absolute_url,'Update')

	return render_to_response('page/page_update.html', locals(),
							context_instance=RequestContext(request) )



@login_required
def page_delete( request, username, slug ):
	""" Delete a page """

	page = get_object_or_404(Page, user__username = username, slug=urlquote(slug) )
	user = page.user
	profile = add_model_chrome(user.get_profile(),request)

	if not page.permission(request.user,'delete'):
		return HttpResponseForbidden()

	if request.method == "POST":

		parent = page.parent
		page.delete()
		request.user.message_set.create(message='Page deleted')

		if None == parent:
			return HttpResponseRedirect( user.get_absolute_url() )
		else:
			return HttpResponseRedirect( parent.get_absolute_url() )

	else:
		form = PageDeleteForm(instance=page)

	# Load breadcrumb of parent pages.
	breadcrumb = ChromeBreadcrumbForm()
	breadcrumb.append(user.get_absolute_url(),user.first_name)
	for p in page.getParentTree():
		breadcrumb.append(p.get_absolute_url(),p.title)
	breadcrumb.append(page.get_absolute_url,'Delete')


	return render_to_response( 'page/page_confirm_delete.html', locals(),
							context_instance=RequestContext(request) )



def pageartifact_read( request, username, slug, id ):
	""" Return a single pageartifact in normal html view """

	artifact = get_object_or_404(PageArtifact, pk=id)
	user = artifact.page.user
	profile = add_model_chrome(user.get_profile(),request)
	page = artifact.page
	artifact = add_model_chrome(artifact,request)

	if not artifact.permission(request.user,'select'):
		return HttpResponseForbidden()

	return render_to_response( 'page/pageartifact_detail.html', locals(),
							context_instance=RequestContext(request)  )


def pageartifact_annotate( request, username, slug, id ):
	""" Return a single pageartifact in an annotatable html view """

	artifact = get_object_or_404(PageArtifact, pk=id)
	user = artifact.page.user
	profile = add_model_chrome(user.get_profile(),request)
	page = artifact.page
	artifact = add_model_chrome(artifact,request)

	# Generate images
	import subprocess

	(path, sep, filename) = artifact.artifact.file.path.rpartition('\\')
	(url, sep, filename) = artifact.artifact.file.url.rpartition('/')
	im = "C:\Program Files\ImageMagick-6.5.4-Q8\convert.exe"
	newpath = "%s\page.png" % path
	ret = subprocess.call('"%s" -density 250 "%s" "%s"' % (im,
													artifact.artifact.file.path,
													newpath))
	# Return image 1
	img = "%s/page-0.png" % url

	if not artifact.permission(request.user,'select'):
		return HttpResponseForbidden()

	return render_to_response( 'page/pageartifact_annotate.html', locals(),
							context_instance=RequestContext(request)  )


def pageartifact_list( request, username, slug ):
	""" Return the list of artifacts belonging to a page """

	page = get_object_or_404(Page, slug=urlquote(slug))
	artifact_list = PageArtifact.objects.filter( page=page )
	user = page.user
	profile = add_model_chrome(user.get_profile(),request)

	artifact_list_header = child_model_chrome_list_header(
					page.title +" Artifact List",
					PageArtifact,
					request.user,
					page)

	return render_to_response( 'page/pageartifact_list.html', locals(),
							context_instance=RequestContext(request)  )



@login_required
def pageartifact_insert( request, username, slug ):
	""" Creates an Artifact using the PageArtifactCreateForm """

	artifact = None
	page = get_object_or_404(Page, slug=urlquote(slug))
	user = page.user
	profile = add_model_chrome(user.get_profile(),request)

	if not PageArtifact.insert_permission(page, request.user):
		return HttpResponseForbidden()

	if request.method == 'POST':
		# Load correct form.
		if request.is_ajax() or request.GET.get('xhr','false') == 'true':
			form = PageArtifactAjaxInsertForm(request.POST, request.FILES)
			form.set_master(page)
		else:
			form = ArtifactInsertForm(request.POST, request.FILES)

		# If valid, save results.
		if form.is_valid():
			artifact = form.save()

			# Create the linking Page->Artifact record.
			pa = PageArtifact()
			pa.artifact = artifact
			pa.page = page
			pa.save()

			# Return correct form type (or redirect)
			if request.is_ajax() or request.GET.get('xhr','false') == 'true':
				# Return result wrapped in a 'wrapper' div so that js can properly
				#	pull the intended html from the returned HTMLDocument.
				form = PageArtifactInlineUpdateForm(instance=pa)
				return HttpResponse( '<div id="wrapper">' + form.as_template() + '</div>' )

			else:
				# Return the absolute link to the artifact.
				request.user.message_set.create(message='Artifact created')
				return HttpResponseRedirect( pa.get_absolute_url() )
		else:
			return HttpResponse('Error uploading file')
	else:
		form = ArtifactInsertForm()


	return render_to_response('page/pageartifact_insert.html',
						{'form':form,'user':user,'page':page},
						context_instance=RequestContext(request) );


@login_required
def pageartifact_update( request, username, slug, id ):
	""" Return a view for updating an Artifact """

	user = get_object_or_404(User, username=username )
	pageartifact = get_object_or_404(PageArtifact, pk=id )
	profile = add_model_chrome(user.get_profile(),request)

	if not pageartifact.permission(request.user,'update'):
		return HttpResponseForbidden()

	forms = ComboForm()
	forms.add_form(PageArtifactUpdateForm, instances=[pageartifact], request=request)
	forms.add_form(ArtifactUpdateForm, instances=[pageartifact.artifact], request=request)

	if request.method == 'POST':
		if forms.is_valid():
			forms.save()
			request.user.message_set.create(message='Artifact updated')
			return HttpResponseRedirect(pageartifact.get_absolute_url())

	return render_to_response('page/pageartifact_update.html', locals(),
							context_instance=RequestContext(request) );


@login_required
def pageartifact_delete( request, username, slug, id ):
	""" Delete an artifact """

	pageartifact = get_object_or_404(PageArtifact, pk=id)
	user = pageartifact.page.user
	page = pageartifact.page
	profile = add_model_chrome(user.get_profile(),request)

	if not pageartifact.permission(request.user,'delete'):
		return HttpResponseForbidden()

	form = ArtifactDeleteForm(instance=pageartifact)

	if request.method == "POST":

		# If the artifact isn't used elsewhere, delete it.
		if len( PageArtifact.objects.filter(artifact=pageartifact.artifact) ) == 1:
			pageartifact.artifact.delete()

		pageartifact.delete()

		if request.is_ajax():
			return HttpResponse("Artifact Deleted")
		else:
			request.user.message_set.create(message='Artifact deleted')
			return HttpResponseRedirect( '%sartifact/' % page.get_absolute_url() )

	return render_to_response('page/pageartifact_confirm_delete.html',
							locals(),
							context_instance=RequestContext(request) )

